package com.demo.function.utils;

import org.apache.commons.collections4.CollectionUtils;

import java.util.*;

public class TreeUtils {

    /**
     * 生成树形结构数据
     * @param list 树形数据
     * @return 数据结构数据集合
     * @param <T> TreeNode接口
     */
    public static <T extends TreeNode> List<T> genTree(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }

        //最终结果集
        List<T> resultList = new ArrayList<>();
        //临时数据集
        Map<Object, TreeNode> objectMap = new HashMap<>();

        //整理数据
        for (TreeNode treeNode : list) {
            //获取主键
            Object o = treeNode.getChildKey();
            objectMap.put(o,treeNode);
        }

        //将结果转换为树形
        for (Map.Entry<Object, TreeNode> objectTEntry : objectMap.entrySet()) {
            TreeNode treeNode = objectTEntry.getValue();
            //获取父级id
            Object pidKey = treeNode.getParentKey();
            //将集合中的顶级放进结果集中
            if (!objectMap.containsKey(pidKey)) {
                resultList.add((T) treeNode);
            } else {
                //将子级数据归类（引用关系）
                TreeNode parent = objectMap.get(pidKey);
                //获取子级
                Collection children = parent.getChildren();
                children.add(treeNode);
            }
        }

        return resultList;
    }
}
